package cn.texous.web.parsing.book.publisher;

import cn.texous.web.parsing.book.model.bo.publisher.EventBO;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/25 18:55
 */
@Component
public class AnaPublisher {

    private static final ConcurrentHashMap<String,
            CopyOnWriteArrayList<AnaSubscribe>> SUB_MAP = new ConcurrentHashMap<>();

    /**
     * 订阅
     *
     * @param subscribe subscribe
     * @return
     */
    public boolean subscribe(AnaSubscribe subscribe) {
        if (SUB_MAP.get(subscribe.getTopic()) == null)
            SUB_MAP.put(subscribe.getTopic(), new CopyOnWriteArrayList<>());
        SUB_MAP.get(subscribe.getTopic()).add(subscribe);
        return true;
    }

    /**
     * 取消订阅
     *
     * @param subscribe 订阅
     * @param topic     主题
     * @return
     */
    public boolean unSubscribe(AnaSubscribe subscribe, String topic) {
        if (SUB_MAP.get(topic) != null)
            SUB_MAP.get(topic).remove(topic);
        return true;
    }

    public <T extends EventBO> void publisher(T object, String topic) {
        if (SUB_MAP.get(topic) != null)
            SUB_MAP.get(topic).forEach(p -> p.onEvent(object));
    }

}
